package com.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.db.common.annotation.RequiredMenu;
import com.db.common.pojo.TreeNode;
import com.db.dao.SysMenuDao;
import com.db.pojo.SysMenu;
import com.db.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class SysMenuServiceImpl implements SysMenuService {

	@Autowired
	private SysMenuDao sysMenuDao;

	@RequiredMenu(operation = "查询菜单")
	@Transactional(readOnly = true)
	@Override
	public List<SysMenu> findObjects() {
		List<SysMenu> list = sysMenuDao.selectList(null);
		return list;
	}

	@RequiredMenu(operation = "删除菜单")
	@Override
	public void deleteById(Integer id) {

		QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
		wrapper.eq("parentId", id);
		Integer rows = sysMenuDao.selectCount(wrapper);
		if (rows > 0)
			throw new RuntimeException("存在子菜单,无法删除");

		sysMenuDao.deleteById(id);
	}

	@RequiredMenu(operation = "新增菜单")
	@Override
	public void insertObject(SysMenu sysMenu) {
		sysMenuDao.insert(sysMenu);
	}

	@RequiredMenu(operation = "查询菜单树")
	@Override
	public List<TreeNode> findTree() {
		List<SysMenu> list = sysMenuDao.selectList(null);

		List<TreeNode> treeNodes = new ArrayList<>();

		for (SysMenu sysMenu :
				list) {
			TreeNode treeNode = new TreeNode();
			treeNode.setId(sysMenu.getId());
			treeNode.setName(sysMenu.getName());
			treeNode.setParentId(sysMenu.getParentId());
			treeNodes.add(treeNode);
		}

		return treeNodes;
	}

	@RequiredMenu(operation = "更新菜单")
	@Override
	public void updateObject(SysMenu sysMenu) {
		sysMenuDao.updateById(sysMenu);
	}
}
